package com.studyweb.controller;

import com.studyweb.pojo.entity.Paper;
import com.studyweb.pojo.entity.PaperQuestion;
import com.studyweb.pojo.entity.QuestionDetail;
import com.studyweb.pojo.vo.Result;
import com.studyweb.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/paper")
@CrossOrigin
public class PaperController {
    
    private static final Logger logger = LoggerFactory.getLogger(PaperController.class);
    
    @Autowired
    private PaperService paperService;
    
    /**
     * 创建试卷
     */
    @PostMapping
    public Result<Paper> createPaper(@RequestBody Paper paper) {
        try {
            logger.info("开始创建试卷: {}", paper.getName());
            Paper createdPaper = paperService.createPaper(paper);
            logger.info("试卷创建成功, ID: {}", createdPaper.getId());
            return Result.success("试卷创建成功", createdPaper);
        } catch (Exception e) {
            logger.error("试卷创建失败", e);
            return Result.error("试卷创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取试卷
     */
    @GetMapping("/{id}")
    public Result<Paper> getPaperById(@PathVariable Long id) {
        try {
            logger.info("开始获取试卷, ID: {}", id);
            Paper paper = paperService.getPaperById(id);
            if (paper != null) {
                logger.info("获取试卷成功, ID: {}", id);
                return Result.success("获取成功", paper);
            } else {
                logger.warn("试卷不存在, ID: {}", id);
                return Result.error(404, "试卷不存在");
            }
        } catch (Exception e) {
            logger.error("获取试卷失败, ID: {}", id, e);
            return Result.error("获取试卷失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有试卷
     */
    @GetMapping
    public Result<List<Paper>> getAllPapers() {
        try {
            logger.info("开始获取所有试卷");
            List<Paper> papers = paperService.getAllPapers();
            logger.info("获取试卷列表成功, 数量: {}", papers.size());
            return Result.success("获取成功", papers);
        } catch (Exception e) {
            logger.error("获取试卷列表失败", e);
            return Result.error("获取试卷列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据条件查询试卷
     */
    @GetMapping("/search")
    public Result<List<Paper>> searchPapers(@RequestParam(required = false) String name) {
        try {
            logger.info("开始搜索试卷, 关键词: {}", name);
            List<Paper> papers = paperService.getPapersByCondition(name);
            logger.info("搜索试卷成功, 数量: {}", papers.size());
            return Result.success("搜索成功", papers);
        } catch (Exception e) {
            logger.error("搜索试卷失败", e);
            return Result.error("搜索试卷失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新试卷
     */
    @PutMapping
    public Result<Paper> updatePaper(@RequestBody Paper paper) {
        try {
            logger.info("开始更新试卷, ID: {}", paper.getId());
            Paper updatedPaper = paperService.updatePaper(paper);
            logger.info("试卷更新成功, ID: {}", paper.getId());
            return Result.success("试卷更新成功", updatedPaper);
        } catch (Exception e) {
            logger.error("试卷更新失败, ID: {}", paper.getId(), e);
            return Result.error("试卷更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除试卷
     */
    @DeleteMapping("/{id}")
    public Result<Void> deletePaper(@PathVariable Long id) {
        try {
            logger.info("开始删除试卷, ID: {}", id);
            paperService.deletePaper(id);
            logger.info("试卷删除成功, ID: {}", id);
            return Result.success(null);
        } catch (Exception e) {
            logger.error("试卷删除失败, ID: {}", id, e);
            return Result.error("试卷删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 为试卷添加题目
     */
    @PostMapping("/{paperId}/questions")
    public Result<Void> addQuestionsToPaper(@PathVariable Long paperId, 
                                           @RequestBody List<PaperQuestion> paperQuestions) {
        try {
            logger.info("开始为试卷添加题目, 试卷ID: {}, 题目数量: {}", paperId, paperQuestions.size());
            paperService.addQuestionsToPaper(paperId, paperQuestions);
            logger.info("为试卷添加题目成功, 试卷ID: {}", paperId);
            return Result.success(null);
        } catch (Exception e) {
            logger.error("题目添加失败, 试卷ID: {}", paperId, e);
            return Result.error("题目添加失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取试卷的所有题目
     */
    @GetMapping("/{paperId}/questions")
    public Result<Map<String, List<QuestionDetail>>> getPaperQuestions(@PathVariable Long paperId) {
        try {
            logger.info("开始获取试卷题目, 试卷ID: {}", paperId);
            Map<String, List<QuestionDetail>> questionsWithDetails = paperService.getPaperQuestionsWithDetails(paperId);
            
            // 记录每个模块的题目数量
            for (Map.Entry<String, List<QuestionDetail>> entry : questionsWithDetails.entrySet()) {
                logger.info("模块: {}, 题目数量: {}", entry.getKey(), entry.getValue().size());
            }
            
            logger.info("获取试卷题目成功, 试卷ID: {}", paperId);
            return Result.success("获取成功", questionsWithDetails);
        } catch (Exception e) {
            logger.error("获取试卷题目失败, 试卷ID: {}", paperId, e);
            return Result.error("获取试卷题目失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除试卷中的所有题目
     */
    @DeleteMapping("/{paperId}/questions")
    public Result<Void> deletePaperQuestions(@PathVariable Long paperId) {
        try {
            logger.info("开始删除试卷中的所有题目, 试卷ID: {}", paperId);
            paperService.deletePaperQuestions(paperId);
            logger.info("删除试卷中的所有题目成功, 试卷ID: {}", paperId);
            return Result.success(null);
        } catch (Exception e) {
            logger.error("删除试卷中的所有题目失败, 试卷ID: {}", paperId, e);
            return Result.error("删除试卷中的所有题目失败: " + e.getMessage());
        }
    }
    
    /**
     * 从试卷中删除指定的题目
     */
    @DeleteMapping("/{paperId}/questions/{questionId}")
    public Result<Void> removeQuestionFromPaper(@PathVariable Long paperId, 
                                               @PathVariable Long questionId) {
        try {
            logger.info("开始从试卷中删除题目, 试卷ID: {}, 题目ID: {}", paperId, questionId);
            paperService.removeQuestionFromPaper(paperId, questionId);
            logger.info("从试卷中删除题目成功, 试卷ID: {}, 题目ID: {}", paperId, questionId);
            return Result.success(null);
        } catch (Exception e) {
            logger.error("从试卷中删除题目失败, 试卷ID: {}, 题目ID: {}", paperId, questionId, e);
            return Result.error("从试卷中删除题目失败: " + e.getMessage());
        }
    }
}